import fs from "fs";
import { tools } from "./tools/tools";

export namespace resource_check {
    export class ResourceChecker {
        constructor(entery: string, cfgFilePath?: string) {
            this.curRoot = entery;
            if (!!cfgFilePath) {
                this.CfgAnalyze([JSON.parse(fs.readFileSync(this.PathGenrator(`/resource/${cfgFilePath}`), { encoding: 'utf-8' }))]);
            } else {
                tools.GlobFile(['*.json'], '', {
                    nodir: true,
                    cwd: this.curRoot + '/resource/',
                }).then(matches => {
                    let cfgs: tools.RES_FILE_TYPE[] = [];
                    matches.forEach(match => {
                        let tmp = JSON.parse(fs.readFileSync(this.PathGenrator(`/resource/${match}`), { encoding: 'utf-8' }));
                        if (tmp && !!tmp.groups && !!tmp.resources) {
                            cfgs.push(tmp);
                        }
                    });

                    this.CfgAnalyze(cfgs);
                });
            }
        }

        private CfgAnalyze(cfgFiles: tools.RES_FILE_TYPE[]): void {
            if (!cfgFiles || cfgFiles.length < 1) {
                return;
            }
            let rootFolder: string[] = [];
            let paths: string[] = [];
            let root: string;
            for (let cfgFile of cfgFiles) {
                for (let res of cfgFile.resources) {
                    root = res.url.split('/').length > 1 ? res.url.split('/')[0] : '';
                    root && rootFolder.indexOf(root + '/**') < 0 && rootFolder.push(root + '/**');
                    res.url && res.url.split('/').length > 1 && paths.indexOf(res.url) < 0 && paths.push(res.url);
                }
            }

            tools.GlobFile(rootFolder, '', {
                cwd: this.curRoot + '/resource/',
                nodir: true
            }).then(result => {
                let overArr: string[] = [];
                result.forEach(path => {
                    if (path.indexOf('.exml') < 0 && paths.indexOf(path) < 0) {
                        overArr.push(path);
                    }
                });

                if (overArr.length > 0) {
                    console.log(`cfgNum: ${paths.length}, fileNum: ${result.length}`);
                    console.log(overArr.length);
                    console.log(JSON.stringify(overArr, null, '\t'));
                }
            });
        }

        private PathGenrator(tmpPath: string): string {
            return `${this.curRoot}/${tmpPath}`;
        }

        private curRoot: string;
    }
}